<template>
	<view class="page">
		<!-- 搜索栏 -->
		<view class="search-container">
			<view class="search-box">
				<uni-icons type="search" size="18" color="#999"></uni-icons>
				<input class="search-input" placeholder="搜索客户姓名或编号" placeholder-style="color: #999;"
					v-model="searchKeyword" @input="handleSearch" />
				<view v-if="searchKeyword" @tap="clearSearch" class="clear-icon">
					<uni-icons type="clear" size="18" color="#999"></uni-icons>
				</view>
			</view>
		</view>

		<!-- 列表内容 -->
		<view id="content">
			<scroll-view scroll-y :style="{height: scrollHeight + 'px'}" @scrolltolower="loadMore"
				:refresher-enabled="true" :refresher-triggered="refreshing" @refresherrefresh="onRefresh">
				<!-- 空状态 -->
				<view v-if="flowList.length === 0" class="empty-state">
					<image src="/static/images/empty.png" class="empty-image" mode="aspectFit"></image>
					<text class="empty-text">暂无流水记录</text>
				</view>

				<!-- 流水列表 -->
				<view v-else>
					<view class="flow-card" v-for="(item, index) in flowList" :key="item.id || index">
						<view class="card-header">
							<view class="customer-info">
								<text class="customer-name">{{item.customerName}}</text>
								<text class="flow-status" >
									<!-- :class="getStatusClass(item.status)" -->
									{{getStatusText(item.status)}}
								</text>
							</view>
							<text class="flow-no">{{item.no}}</text>
						</view>

						<view class="card-content">
							<view class="amount-section">
								<text class="amount-label">金额</text>
								<text class="amount-value">¥{{formatPrice(item.amount)}}</text>
							</view>

							<view class="info-section">
								<view class="info-item">
									<text class="info-label">类型：</text>
									<text class="info-value">{{getFlowTypeText(item.flowType)}}</text>
								</view>
								<view class="info-item" v-if="item.paymentMethod && item.status !== 1">
									<text class="info-label">支付方式：</text>
									<text class="info-value">{{getPaymentMethodText(item.paymentMethod)}}</text>
								</view>
								<view class="info-item" v-if="item.createTime">
									<text class="info-label">时间：</text>
									<text class="info-value">{{formatTime(item.createTime)}}</text>
								</view>
							</view>

							<!-- 待支付状态的支付信息填写区域 -->
							<view v-if="item.status === 1" class="payment-info-section">
								<view class="section-title">
									<text>支付信息</text>
								</view>

								<!-- 支付方式选择 -->
								<view class="form-item">
									<text class="form-label">支付方式</text>
									<picker @change="(e) => handlePaymentMethodChange(e, item)"
										:value="item.selectedPaymentMethod || 0" :range="paymentMethodOptions"
										range-key="label" class="payment-picker">
										<view class="picker-content">
											<text>{{getPaymentMethodText(item.selectedPaymentMethod) || '请选择支付方式'}}</text>
											<uni-icons type="arrowdown" size="16" color="#999"></uni-icons>
										</view>
									</picker>
								</view>

								<!-- 流水号输入 -->
								<view class="form-item">
									<text class="form-label">流水号</text>
									<input class="form-input" v-model="item.flowNumber" placeholder="请输入流水号"
										placeholder-style="color: #ccc;"
										@input="(e) => handleInputChange(e, item, 'flowNumber')" />
								</view>
								
								
								<view class="form-item">
									<text class="form-label">实际金额</text>
									<uni-easyinput v-model="item.convertedAmount" placeholder="请输入金额"></uni-easyinput>
									<!-- <input class="form-input" v-model="item.flowNumber" placeholder="请输入流水号"
										placeholder-style="color: #ccc;"
										@input="(e) => handleInputChange(e, item, 'flowNumber')" /> -->
								</view>

								<!-- 对方账户信息输入 -->
								<view class="form-item">
									<text class="form-label">对方账户信息</text>
									<input class="form-input" v-model="item.accountInfo" placeholder="请输入对方账户信息"
										placeholder-style="color: #ccc;"
										@input="(e) => handleInputChange(e, item, 'accountInfo')" />
								</view>
								

								<!-- 操作按钮 -->
								<view class="action-buttons">
									<button class="action-btn cancel-btn" @tap="handleCancel(item)"
										:disabled="item.processing">
										{{item.processing ? '处理中...' : '取消支付'}}
									</button>
									<button class="action-btn confirm-btn" @tap="handleConfirm(item)"
										:disabled="item.processing || !isPaymentInfoValid(item)"
										:class="{disabled: item.processing || !isPaymentInfoValid(item)}">
										{{item.processing ? '处理中...' : '确认支付'}}
									</button>
								</view>
							</view>

							<!-- 非待支付状态显示支付信息 -->
							<view v-else-if="item.status === 2 || item.status === 4" class="completed-payment-info">
								<view class="section-title">
									<text>支付信息</text>
								</view>
								<view class="info-grid">
									<view class="info-cell">
										<text class="info-cell-label">支付方式：</text>
										<text
											class="info-cell-value">{{getPaymentMethodText(item.paymentMethod)}}</text>
									</view>
									<view class="info-cell" v-if="item.flowNumber">
										<text class="info-cell-label">流水号：</text>
										<text class="info-cell-value">{{item.flowNumber}}</text>
									</view>
									<view class="info-cell" v-if="item.accountInfo">
										<text class="info-cell-label">对方账户：</text>
										<text class="info-cell-value">{{item.accountInfo}}</text>
									</view>
								</view>
							</view>
						</view>
					</view>

					<!-- 加载更多 -->
					<view v-if="loadingMore" class="load-more">
						<uni-load-more status="loading"></uni-load-more>
					</view>
					<view v-if="noMoreData" class="load-more">
						<text class="no-more-text">没有更多数据了</text>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				flowList: [],
				searchKeyword: '',
				refreshing: false,
				loadingMore: false,
				noMoreData: false,
				currentPage: 1,
				pageSize: 10,
				scrollHeight: 0,
				paymentMethodOptions: [{
						label: '现金',
						value: 1
					},
					{
						label: '银行卡',
						value: 2
					},
					{
						label: '微信支付',
						value: 3
					},
					{
						label: '支付宝',
						value: 4
					},
					{
						label: 'POS机',
						value: 5
					}
				]
			};
		},
		onLoad(query) {
			if (query && query.type == 1) {
				this.getHouseInten();
			}
			this.calcScrollHeight();
		},
		onReady() {
			this.calcScrollHeight();
		},
		onShow() {
			// 页面显示时刷新数据
			this.loadData(true);
		},
		methods: {
			// 计算滚动区域高度
			calcScrollHeight() {
				const query = uni.createSelectorQuery().in(this);
				query.select('#content').boundingClientRect(data => {
					if (data) {
						const systemInfo = uni.getSystemInfoSync();
						const windowHeight = systemInfo.windowHeight;
						this.scrollHeight = windowHeight - data.top;
					}
				}).exec();
			},

			// 加载数据
			async loadData(refresh = false) {
				if (refresh) {
					this.currentPage = 1;
					this.noMoreData = false;
				}

				const params = {
					page: this.currentPage,
					pageSize: this.pageSize,
					status: 1,
					flowType: 1,
					keyword: this.searchKeyword || undefined
				};

				try {
					const res = await this.$cloudOBjAjax('customer-flow', 'getList', params);
					const newList = res.list || [];

					// 初始化支付信息填写状态
					const processedList = newList.map(item => ({
						...item,
						selectedPaymentMethod: item.paymentMethod || undefined,
						flowNumber: item.flowNumber || '',
						accountInfo: item.accountInfo || '',
						processing: false ,// 防止重复提交
						convertedAmount:item.amount
					}));

					if (refresh) {
						this.flowList = processedList;
					} else {
						this.flowList = [...this.flowList, ...processedList];
					}

					// 判断是否还有更多数据
					if (newList.length < this.pageSize) {
						this.noMoreData = true;
					}
				} catch (error) {
					console.error('加载数据失败:', error);
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				} finally {
					this.refreshing = false;
					this.loadingMore = false;
				}
			},

			// 下拉刷新
			onRefresh() {
				this.refreshing = true;
				this.loadData(true);
			},

			// 上拉加载
			loadMore() {
				if (this.loadingMore || this.noMoreData) return;

				this.loadingMore = true;
				this.currentPage++;
				this.loadData(false);
			},

			// 搜索处理
			handleSearch() {
				clearTimeout(this.searchTimer);
				this.searchTimer = setTimeout(() => {
					this.loadData(true);
				}, 300);
			},

			// 清空搜索
			clearSearch() {
				this.searchKeyword = '';
				this.loadData(true);
			},

			// 支付方式选择
			handlePaymentMethodChange(e, item) {
				const index = e.detail.value;
				const paymentMethod = this.paymentMethodOptions[index].value;

				// 更新item的选中支付方式
				const itemIndex = this.flowList.findIndex(i => i.id === item.id);
				if (itemIndex > -1) {
					this.$set(this.flowList[itemIndex], 'selectedPaymentMethod', paymentMethod);
				}
			},

			// 输入框变化
			handleInputChange(e, item, field) {
				const value = e.detail.value;
				const itemIndex = this.flowList.findIndex(i => i.id === item.id);
				if (itemIndex > -1) {
					this.$set(this.flowList[itemIndex], field, value);
				}
			},

			// 验证支付信息是否完整
			isPaymentInfoValid(item) {
				return item.selectedPaymentMethod &&
					item.flowNumber &&
					item.flowNumber.trim() &&
					item.accountInfo &&
					item.accountInfo.trim();
			},

			// 确认支付
			async handleConfirm(item) {
				if (!this.isPaymentInfoValid(item)) {
					uni.showToast({
						title: '请填写完整的支付信息',
						icon: 'none'
					});
					return;
				}

				uni.showModal({
					title: '确认支付',
					content: `确认收到客户 ${item.customerName} 的 ¥${this.formatPrice(item.price)} 支付吗？`,
					success: async (res) => {
						if (res.confirm) {
							// 设置处理中状态
							const itemIndex = this.flowList.findIndex(i => i.id === item.id);
							if (itemIndex > -1) {
								this.$set(this.flowList[itemIndex], 'processing', true);
							}

							try {
								// 调用支付确认接口
								await this.confirmPayment(item);
								uni.showToast({
									title: '支付确认成功',
									icon: 'success'
								});
								// 重新加载数据
								this.loadData(true);
							} catch (error) {
								// 恢复处理状态
								if (itemIndex > -1) {
									this.$set(this.flowList[itemIndex], 'processing', false);
								}
								uni.showToast({
									title: '支付确认失败',
									icon: 'none'
								});
							}
						}
					}
				});
			},

			// 支付确认接口调用
			async confirmPayment(item) {
				const paymentData = {
					id: item.id,
					status: 2, // 支付成功
					paymentMethod: item.selectedPaymentMethod,
					flowNumber: item.flowNumber,
					accountInfo: item.accountInfo
				};

				return await this.$cloudOBjAjax('customer-flow', 'confirmPayment', paymentData);
			},

			// 取消支付
			async handleCancel(item) {
				uni.showModal({
					title: '取消支付',
					content: `确认取消客户 ${item.customerName} 的支付记录吗？`,
					success: async (res) => {
						if (res.confirm) {
							// 设置处理中状态
							const itemIndex = this.flowList.findIndex(i => i.id === item.id);
							if (itemIndex > -1) {
								this.$set(this.flowList[itemIndex], 'processing', true);
							}

							try {
								await this.cancelPayment(item.id);
								uni.showToast({
									title: '取消成功',
									icon: 'success'
								});
								// 重新加载数据
								this.loadData(true);
							} catch (error) {
								// 恢复处理状态
								if (itemIndex > -1) {
									this.$set(this.flowList[itemIndex], 'processing', false);
								}
								uni.showToast({
									title: '取消失败',
									icon: 'none'
								});
							}
						}
					}
				});
			},

			// 取消支付接口调用
			async cancelPayment(id) {
				return await this.$cloudOBjAjax('customer-flow', 'cancelPayment', {
					id,
					status: 3
				});
			},

			// 格式化价格
			formatPrice(price) {
				if (!price) return '0.00';
				return Number(price).toFixed(2);
			},

			// 格式化时间
			formatTime(time) {
				if (!time) return '';
				return time.length > 10 ? time.slice(0, 10) : time;
			},

			// 获取状态样式类
			getStatusClass(status) {
				const classMap = {
					1: 'status-pending',
					2: 'status-success',
					3: 'status-failed',
					4: 'status-refunded',
					5: 'status-converted'
				};
				return classMap[status] || '';
			},

			// 原有的 getHouseInten 方法
			async getHouseInten() {
				// 如果有特殊处理可以保留
				this.loadData(true);
			},

			// 以下为原有的工具函数
			getFlowTypeText,
			getPaymentMethodText,
			getStatusText
		}
	}

	// 工具函数保持不变
	const getFlowTypeText = function(flowType) {
		const typeMap = {
			1: '定金',
			2: '首付款',
			3: '贷款发放',
			4: '尾款',
			5: '退款',
			6: '违约金',
			7: '其他收入',
			8: '其他支出',
			9: '定金转首付款'
		};
		return typeMap[flowType] || '未知';
	}

	const getPaymentMethodText = function(paymentMethod) {
		const methodMap = {
			1: '现金',
			2: '银行卡',
			3: '微信支付',
			4: '支付宝',
			5: 'POS机'
		};
		return methodMap[paymentMethod] || '未知';
	}

	const getStatusText = function(status) {
		const statusMap = {
			1: '待支付',
			2: '支付成功',
			3: '支付失败',
			4: '已退款',
			5: '已转换'
		};
		return statusMap[status] || '未知';
	}
</script>

<style lang="scss">
	.page {
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	// 搜索栏
	.search-container {
		padding: 20rpx 30rpx;
		background: white;

		.search-box {
			display: flex;
			align-items: center;
			padding: 0 24rpx;
			height: 72rpx;
			background: #f5f5f5;
			border-radius: 36rpx;

			.search-input {
				flex: 1;
				font-size: 28rpx;
				margin-left: 16rpx;
				color: #333;
			}

			.clear-icon {
				padding: 8rpx;
			}
		}
	}

	// 流水卡片
	.flow-card {
		background: white;
		margin: 20rpx 30rpx 0;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

		.card-header {
			padding: 30rpx 30rpx 20rpx;
			border-bottom: 1rpx solid #f0f0f0;

			.customer-info {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 16rpx;

				.customer-name {
					font-size: 32rpx;
					font-weight: 600;
					color: #333;
				}

				.flow-status {
					font-size: 24rpx;
					padding: 4rpx 16rpx;
					border-radius: 20rpx;

					&.status-pending {
						background: #fff7e6;
						color: #fa8c16;
					}

					&.status-success {
						background: #f6ffed;
						color: #52c41a;
					}

					&.status-failed {
						background: #fff1f0;
						color: #ff4d4f;
					}

					&.status-refunded {
						background: #f6ffed;
						color: #52c41a;
					}

					&.status-converted {
						background: #e6f7ff;
						color: #1890ff;
					}
				}
			}

			.flow-no {
				font-size: 24rpx;
				color: #999;
			}
		}

		.card-content {
			padding: 30rpx;

			.amount-section {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 30rpx;

				.amount-label {
					font-size: 28rpx;
					color: #666;
				}

				.amount-value {
					font-size: 40rpx;
					font-weight: bold;
					color: #ff6b35;
				}
			}

			.info-section {
				margin-bottom: 30rpx;

				.info-item {
					display: flex;
					margin-bottom: 16rpx;
					font-size: 26rpx;

					.info-label {
						color: #999;
						width: 160rpx;
					}

					.info-value {
						color: #333;
						flex: 1;
					}
				}
			}

			// 支付信息填写区域
			.payment-info-section {
				background: #f9f9f9;
				border-radius: 12rpx;
				padding: 30rpx;
				margin-top: 20rpx;

				.section-title {
					font-size: 28rpx;
					font-weight: 600;
					color: #333;
					margin-bottom: 30rpx;
					padding-bottom: 20rpx;
					border-bottom: 1rpx solid #eee;
				}

				.form-item {
					margin-bottom: 30rpx;

					.form-label {
						display: block;
						font-size: 26rpx;
						color: #666;
						margin-bottom: 16rpx;
					}

					.payment-picker {
						.picker-content {
							display: flex;
							justify-content: space-between;
							align-items: center;
							height: 80rpx;
							padding: 0 24rpx;
							background: white;
							border-radius: 8rpx;
							border: 1rpx solid #e0e0e0;
							font-size: 26rpx;
							color: #333;
						}
					}

					.form-input {
						height: 80rpx;
						padding: 0 24rpx;
						background: white;
						border-radius: 8rpx;
						border: 1rpx solid #e0e0e0;
						font-size: 26rpx;
						color: #333;
					}
				}

				.action-buttons {
					display: flex;
					gap: 20rpx;
					margin-top: 40rpx;

					.action-btn {
						flex: 1;
						margin: 0;
						height: 80rpx;
						line-height: 80rpx;
						font-size: 28rpx;
						border-radius: 8rpx;
						border: none;

						&.cancel-btn {
							background: #f5f5f5;
							color: #666;
						}

						&.confirm-btn {
							background: #007aff;
							color: white;

							&.disabled {
								background: #c0c0c0;
								opacity: 0.6;
							}
						}
					}
				}
			}

			// 已完成的支付信息显示
			.completed-payment-info {
				background: #f9f9f9;
				border-radius: 12rpx;
				padding: 30rpx;
				margin-top: 20rpx;

				.section-title {
					font-size: 28rpx;
					font-weight: 600;
					color: #333;
					margin-bottom: 30rpx;
					padding-bottom: 20rpx;
					border-bottom: 1rpx solid #eee;
				}

				.info-grid {
					.info-cell {
						display: flex;
						margin-bottom: 20rpx;
						font-size: 26rpx;

						.info-cell-label {
							color: #999;
							width: 200rpx;
						}

						.info-cell-value {
							color: #333;
							flex: 1;
							font-weight: 500;
						}
					}
				}
			}
		}
	}

	// 空状态
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 200rpx 0;

		.empty-image {
			width: 240rpx;
			height: 240rpx;
			opacity: 0.6;
		}

		.empty-text {
			margin-top: 40rpx;
			font-size: 28rpx;
			color: #999;
		}
	}

	// 加载更多
	.load-more {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 40rpx 0;

		.no-more-text {
			font-size: 26rpx;
			color: #999;
		}
	}
</style>